package com.fanfan.service.serviceimpl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fanfan.dao.UserDao;
import com.fanfan.enums.AppHttpCodeEnum;
import com.fanfan.exception.SystemException;
import com.fanfan.pojo.Role;
import com.fanfan.pojo.User;
import com.fanfan.pojo.UserInfoVo;
import com.fanfan.pojo.UserRole;
import com.fanfan.pojo.domain.ResponseResult;
import com.fanfan.pojo.vo.*;
import com.fanfan.service.RoleService;
import com.fanfan.service.UserRoleService;
import com.fanfan.service.UserService;
import com.fanfan.utils.BeanCopyUtils;
import com.fanfan.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表(User)表服务实现类
 *
 * @author fansea
 * @since 2022-12-27 17:55:36
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RoleService roleService;

    @Override
    public ResponseResult userInfo() {
        //获取当前登录userid
        Long userId = SecurityUtils.getUserId();
        //查询对应用户信息
        User user=getById(userId);
        //bean拷贝vo对象
        UserInfoVo userInfoVo = BeanCopyUtils.copyOne(user, UserInfoVo.class);
        return ResponseResult.okResult(userInfoVo);
    }

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if(userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        if (phoneNumberExit(user.getPhonenumber())){
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }
        if (emailExit(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        //...
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        //存入数据库
        save(user);
        return ResponseResult.okResult();
    }

    private boolean emailExit(String email) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail,email);
        int count = count(queryWrapper);
        return count>0;
    }

    private boolean phoneNumberExit(String phonenumber) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,phonenumber);
        int count = count(queryWrapper);
        return count>0;
    }

    @Override
    public ResponseResult listUser(Integer pageNum, Integer pageSize, User user) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.like(StringUtils.hasText(user.getUserName()),User::getUserName,user.getUserName());
        queryWrapper.like(StringUtils.hasText(user.getPhonenumber()),User::getPhonenumber,user.getPhonenumber());
        Page<User> page=new Page();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page(page,queryWrapper);
        List<UserVo> userVos = BeanCopyUtils.copyList(page.getRecords(),UserVo.class);
        PageVo pageVo=new PageVo(userVos,page.getTotal());
        return ResponseResult.okResult(pageVo);

    }

    @Override
    public ResponseResult addUser(UserDto userDto) {
        User user = BeanCopyUtils.copyOne(userDto, User.class);
        register(user);
        List<UserRole> userRoles = userDto.getRoleIds().stream()
                .map(id -> new UserRole(user.getId(), id))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoles);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult showUser(Long id) {
        User user = getBaseMapper().selectById(id);
        UserVco userVco = BeanCopyUtils.copyOne(user, UserVco.class);
        LambdaQueryWrapper<UserRole> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(UserRole::getUserId,id);
        List<Long> roleIds = userRoleService.getBaseMapper().selectList(queryWrapper).stream()
                .map(m -> m.getRoleId()).collect(Collectors.toList());
        List<Role> roles = roleService.getBaseMapper().selectList(null);
        return ResponseResult.okResult(new UserVio(roleIds,roles,userVco));

    }

    @Override
    public ResponseResult updateUser(UserDto userDto) {
        User user = BeanCopyUtils.copyOne(userDto, User.class);
        getBaseMapper().updateById(user);
        List<UserRole> userRoles = userDto.getRoleIds().stream()
                .map(id -> new UserRole(user.getId(), id))
                .collect(Collectors.toList());
        //TODO 修复bug
        LambdaQueryWrapper<UserRole> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,user.getId());
        userRoleService.getBaseMapper().delete(queryWrapper);
        userRoleService.saveBatch(userRoles);
        return ResponseResult.okResult();

    }

    @Override
    public ResponseResult OrderInfo() {
        try {
            Long userId = SecurityUtils.getUserId();
            User user = getBaseMapper().selectById(userId);
            UserOrderInfoVo userOrderInfoVo = BeanCopyUtils.copyOne(user, UserOrderInfoVo.class);
            return ResponseResult.okResult(userOrderInfoVo);
        }catch (Exception e){
            throw new SystemException(AppHttpCodeEnum.NEED_LOGIN);
        }

    }

    public boolean userNameExist(String name){
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,name);
        int count = count(queryWrapper);
        return count>0;
    }
    public boolean nickNameExist(String name){
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName,name);
        int count = count(queryWrapper);
        return count>0;
    }


}






